import time

from flask import Blueprint, request, jsonify, make_response
from flask_restful import Api,Resource
from flask import current_app as app
from uitils.comm import get_data
from db import db1
from uitils.acl import aci
from uitils.jwton import jwte
from uitils.redison import red


userbp = Blueprint('userbp',__name__)



@userbp.route('/login',methods=['POST'])
def login():
    data = get_data()
    # 用户账号与密码
    username = data['username']
    password = data['password']
    # 判断用户名与密码是否正确
    sql = "select * from users where name='{}' and password='{}'".format(username,password)
    res = db1.find(sql)
    if not res:
        # 不存在直接返回
        return jsonify({'code':200,'msg':'用户名或密码错误,请重新输入'})
    starttime = time.time()
    # 生成token
    data = {'data': {"username": res['name'], 'uid': res['id'], "iat": starttime, "exp": 3600}}
    token = jwte.jwt_en(data)
    # 获取用户页面权限
    # pagelist = aci.get_page_reslist(res['id'])
    # print(pagelist)
    # 获取接口页面权限
    interfacelist = aci.get_interface_reslist(res['id'])
    key = 'interfacelists'+str(res['id'])
    red.set_add(key,interfacelist)
    return jsonify({'code':200,'token':token,'pagelist':interfacelist,'userid':res['id'],'username':res['name'],'msg':'登录成功'})



def getdata(data):
    list = []
    idlist = []
    for i in data:
        id = i['pid']
        if id not in idlist:
            list.append({'id':id,'name':i['pname'],'son':[]})
            idlist.append(id)
    # 遍历顶级列表,在遍历数据.把子类添加到顶级列表中
    for j,val in enumerate(list):
        for i in data:
            if val['id'] == i['pid']:
                list[j]['son'].append({'id':i['id'],'name':i['name'],'url':i['url']})
    return list


@userbp.route('/getresources')
def getresources():
    uid = request.args.get('userid')
    time.sleep(2)
    data = aci.get_user_reslist(uid)
    res = getdata(data)
    return jsonify({'code':200,'list':res})


@userbp.route('/roles')
def roles():
    sql = "select * from roles"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@userbp.route('/resource')
def resource():
    id = request.args.get('id')
    if id:
        sql = 'select resource_id from role_resource where role_id={}'.format(id)
        res = db1.findall(sql)
        list = []
        for i in res:
            list.append(i['resource_id'])
    else:
        time.sleep(1)
        sql = 'select * from resources'
        list = db1.findall(sql)
    return jsonify({'code':200,'list':list})


@userbp.route('/setrole',methods=['GET','POST'])
def setsole():
    if request.method == 'POST':
        data = get_data()
        # 先删除已有的资源
        id = request.args.get('id')
        sql = 'delete from role_resource where role_id={}'.format(int(id))
        db1.update(sql)
        # 配置新的资源
        ids = []
        for i in data.values():
            ids.append(i)
        for i in ids:
            sql1 = 'insert into role_resource(role_id,resource_id) values({},{})'.format(int(id),i)
            db1.update(sql1)
        return jsonify({'code':200,'msg':'配置成功'})



